# user-service/src/user_service/main.py（同步版）
from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.orm import Session  # 替换 AsyncSession，用同步 Session
import uvicorn
from signal import SIGINT, SIGTERM
# 去掉 asyncio 导入（不再需要异步线程）
from . import crud, models, schemas
from .database import engine, get_db  # 同步 engine 和 get_db
from common.consul_utils import consul_service

# 创建数据库表（同步 engine，不变）
models.Base.metadata.create_all(bind=engine)

app = FastAPI(title="User Service")

# 1. 健康检查接口（async def → def，去掉 await）
@app.get("/health", tags=["system"])
def health_check():  # 无 async
    return {"status": "healthy", "service": "user-service"}

# 2. 创建用户（路由同步化）
@app.post("/users/", response_model=schemas.User)
def create_user(  # async def → def
    user: schemas.UserCreate, 
    db: Session = Depends(get_db)  # db 类型换 Session
):
    db_user = crud.get_user_by_email(db, email=user.email)  # 去掉 await
    if db_user:
        raise HTTPException(status_code=400, detail="Email already registered")
    return crud.create_user(db=db, user=user)  # 去掉 await

# 3. 获取用户（同步化）
@app.get("/users/{user_id}", response_model=schemas.User)
def read_user(  # async def → def
    user_id: int, 
    db: Session = Depends(get_db)
):
    db_user = crud.get_user(db, user_id=user_id)  # 去掉 await
    if db_user is None:
        raise HTTPException(status_code=404, detail="User not found")
    return db_user

# 4. 获取用户列表（同步化）
@app.get("/users/", response_model=list[schemas.User])
def read_users(  # async def → def
    skip: int = 0, 
    limit: int = 100, 
    db: Session = Depends(get_db)
):
    users = crud.get_users(db, skip=skip, limit=limit)  # 去掉 await
    return users

# 5. 服务注册/注销事件（同步化，去掉 async/await 和 asyncio.to_thread）
def startup_event():  # async def → def
    """同步注册服务（直接调用，无需异步线程）"""
    consul_service.register_service(
        service_name="user-service",
        service_port=8001,
        tags=["user", "microservice"]
    )

def shutdown_event():  # async def → def
    """同步注销服务"""
    consul_service.deregister_service()

# 注册事件（不变）
app.add_event_handler("startup", startup_event)
app.add_event_handler("shutdown", shutdown_event)

if __name__ == "__main__":
    uvicorn.run("user_service.main:app", host="0.0.0.0", port=8001, reload=True)